import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import viteImagemin from 'vite-plugin-imagemin'

// https://vitejs.dev/config/
export default defineConfig({
  base: '/',
  plugins: [
    vue(),
    // 图片压缩插件 - 只在生产构建时启用
    viteImagemin({
      // PNG压缩配置
      optipng: {
        optimizationLevel: 7, // 压缩级别 0-7，7为最高压缩
      },
      pngquant: {
        quality: [0.6, 0.8], // 压缩质量范围 60%-80%
        speed: 11, // 压缩速度 1-11，4为平衡速度和质量
      },
      // JPEG压缩配置（如果有JPEG图片）
      mozjpeg: {
        quality: 80,
      },
      // SVG压缩配置
      svgo: {
        plugins: [
          {
            name: 'removeViewBox',
          },
          {
            name: 'removeEmptyAttrs',
            active: false,
          },
        ],
      },
    }),
  ],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  },
  server: {
    port: 5173,
    open: true
  },
  build: {
    outDir: 'dist',
    // 静态资源处理
    assetsInlineLimit: 4096, // 小于4kb的资源内联为base64
    rollupOptions: {
      output: {
        // 静态资源分类输出
        assetFileNames: (assetInfo) => {
          const info = assetInfo.name?.split('.') || []
          let extType = info[info.length - 1]
          if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name || '')) {
            extType = 'media'
          } else if (/\.(png|jpe?g|gif|svg)(\?.*)?$/i.test(assetInfo.name || '')) {
            extType = 'images'
          } else if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name || '')) {
            extType = 'fonts'
          }
          return `assets/${extType}/[name]-[hash][extname]`
        },
      },
    },
  },
  esbuild: {
    // 生产环境移除console调试信息
    drop: ['console', 'debugger']
  }
})